package org.newlucene.core.search;

import java.io.IOException;

import org.newlucene.core.index.*;

public class ExactPhraseSearcher extends PhraseSearcher
{
	Term[] terms;
	
	public ExactPhraseSearcher(IndexReader indexReader, Term[] terms) throws IOException
	{
		super(indexReader, terms);
		this.terms = terms;
	}
	   
    protected final float phraseFreq() throws IOException
    {
        // sort list with pq
        for (PhrasePositions pp = first; pp != null; pp = pp.next)
        {
            pp.firstPosition();
            pq.put(pp); // build pq from list
        }
        pqToList(); // rebuild list from pq

        int freq = 0;
        do
        { // find position w/ all terms
            while (first.position < last.position)
            { // scan forward in first
                do
                {
                    if (!first.nextPosition()) return (float) freq;
                }
                while (first.position < last.position);
                firstToLast();
            }
            freq++; // all equal: a match
        }
        while (last.nextPosition());

        return (float) freq;
    }

    public String explain()
    {
    	// build the keyword string
    	StringBuilder sb = new StringBuilder();
    	// field name
    	sb.append(terms[0].field()).append(":");
    	// field value
    	sb.append("\"");
    	for (Term term : terms)
    	{
    		sb.append(term.text()).append(" ");
    	}
    	sb.deleteCharAt(sb.length() - 1); // delete last white space
    	sb.append("\"");
    	// boost
    	if (boost != 1.0f)
    	{
    		sb.append("^").append(boost);
    	}
    	return sb.toString();
    }
}